const iconv = require('iconv-lite') //中文转码
const fs = require('fs');
const request = require('request');
const apiUrl ='https://dataapi.joinquant.com/apis'

/**
 * 
 * @param {*} obj JQdate 请求返回的body
 * @param {*} FilName 文件取名规则：股票代码 + 打印的记录日期
 */
async function exportExcle(obj, FilName) {
    
    return new Promise((resolve, reject) => {
        // 生成csv文件
        fs.writeFile('./股票/' + FilName + '.csv', obj, function (err) {
            if (err) {
                reject({ err });
            } else {
                resolve(FilName);
            }
        })
    })
}
let endDay
let beginDay
let all = 37;
var gpData;
let EventEmitter = require('events');
let msg = new EventEmitter();

/**
 * 用于判断时间周期
 * @param {*} start 下载记录开始时间
 * @param {*} end 下载记录结束时间
 */
async function isDowload(data , fPath) {   
    
    all--
    var end = new Date(new Date(data.end_date).toDateString()).getTime();
    console.log('all===================',data) 
    // console.log('fPath===================',fPath) 
    myDowload(data , fPath); 
    if(all==0){
        
        console.log('发信息了')
        msg.emit('test1')
        all= 37;
    }else if(!beginDay){
        beginDay = data.end_date;
        gpData = data;
        // myDowload(data , fPath);       
    }else{
        beginDay = new Date(new Date(data.end_date).toDateString()).getTime()- (24*60*60*1000)*29 ;
        var endDate = new Date(beginDay);
        var Y = endDate.getFullYear() + '-';
        var M = (endDate.getMonth() + 1 < 10 ? '0' + (endDate.getMonth() + 1) : endDate.getMonth() + 1) + '-';
        var D = (endDate.getDate()  < 10 ? '0' + endDate.getDate() : endDate.getDate()) + '' ;
        // endDay = Y+M+D;
        endDay = '2020-10-19';
        data.end_date = '2020-10-19';
        gpData = data;
        // console.log('D============',D)
        // myDowload(data , fPath);
    }
}
async function myDowload(data , fPath) {		
       console.log(data)
    request({
        url: apiUrl,
        method: "POST",
        body: JSON.stringify(data)
    }, function (error, response, body) {         
        exportExcle(body, fPath + '/' + data.code + '-' + data.end_date).then((response) =>{				
                if(all > 0){
                    isDowload( gpData, fPath)
                }
        });
        return true;	
    });
};



module.exports = {
    exportExcle,
    isDowload,
    myDowload
}